import {
  OnGatewayConnection,
  OnGatewayDisconnect,
  WebSocketGateway,
  WebSocketServer
} from '@nestjs/websockets';
import { Socket } from 'socket.io';

@WebSocketGateway()
export class EventsGateway implements OnGatewayConnection, OnGatewayDisconnect {
  private clientIdMap: Map<string, Socket> = new Map<string, Socket>([]);
  private userClientMap: Map<string, Socket> = new Map<string, Socket>([]);

  @WebSocketServer()
  private server: Socket;

  handleConnection(client: Socket): boolean {
    const token = client.handshake.auth.token;
    // TODO check token
    if (!token) {
      client.disconnect();
      return false;
    }

    const userId = `${client.handshake.query.userId}`;

    this.clientIdMap.set(client.id, client);
    this.userClientMap.set(userId, client);

    this.server.emit('online', userId);
  }

  handleDisconnect(client: Socket): void {
    const userId = this.clientIdMap.get(client.id).handshake.query.userId;
    this.clientIdMap.delete(client.id);
    this.userClientMap.delete(`${userId}`);

    this.server.emit('offline', userId);
  }
}
